package com.itheima.pinda.authority.biz.service.auth.impl;

import cn.hutool.core.util.StrUtil;
import com.itheima.pinda.authority.biz.service.auth.ValidateCodeService;
import com.itheima.pinda.common.constant.CacheKey;
import com.itheima.pinda.exception.BizException;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import net.oschina.j2cache.CacheChannel;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 校验验证码接口实现类
 *
 * @author zhangjy
 * @date 2023/9/25
 */
@Service
@Slf4j
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Resource
    private CacheChannel cacheChannel;

    @Override
    public void create(String key, HttpServletResponse response) {
        try {
            if (StrUtil.isBlank(key)) {
                throw new BizException("验证码key不能为空");
            }

            // 生成纯数字验证码
            ArithmeticCaptcha captcha = new ArithmeticCaptcha();
            captcha.setCharType(2);
            String captchaText = captcha.text();
            // 放入缓存
            cacheChannel.set(CacheKey.CAPTCHA, key, captchaText);

            // 放入response
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
            // 避免出现浏览器缓存
            response.setHeader(HttpHeaders.PRAGMA, "No-cache");
            response.setHeader(HttpHeaders.CACHE_CONTROL, "No-cache");
            response.setDateHeader(HttpHeaders.EXPIRES, 0L);
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            log.error("生成验证码失败：{}", key, e);
            throw new BizException("生成验证码失败：" + key);
        }
    }

}
